<?php
/**
 * 帖子模型类
 */

class PostModel extends Model
{
    private $post_id;

    const REWARD = 1;//悬赏
    const PRAISE = 2;//赞赏
    const CROWDFUNDING = 3;//心愿
    const NORMAL = 4;//普通

    /**
     * 构造函数
     * @author 姜伟
     * @todo 构造函数
     */
    public function __construct($post_id=0)
    {
        parent::__construct();
        $this->post_id = $post_id;
    }


    public function postTypeName(){
        return array(
            self::REWARD => '悬赏',
            self::PRAISE => '赞赏',
            self::CROWDFUNDING => '心愿',
            self::NORMAL => '普通',
            );
    }

    public function postType(){
        return array(
            self::REWARD => 'reward',
            self::PRAISE => 'praise',
            self::CROWDFUNDING => 'crowdfunding',
            self::NORMAL => 'normal',
            );
    }


    public function getPostInfo($where){
        return $this->where($where)->find();
    }

    public function getPostField($where,$field){
        return $this->where($where)->getField($field);
    }
    public function getPostFields($where,$field){
        return $this->where($where)->getField($field,true);
    }

    //获取今日新帖数
    public function getTodayPostNum($channel_id){
        $start_time = strtotime(date('Y-m-d'));
        $end_time = $start_time + 86400;
        return $this->where('addtime >= '.$start_time. ' and addtime <'.$end_time. ' and channel_id ='.$channel_id)->count();
    }
    //符合要求的帖子數
    public function getPostNum($where){
        return $this->where($where)->count();
    }


    //添加帖子
    public function addPost($arr){
        if(!is_array($arr)) return false;
        $arr['addtime'] = time();
        $arr['updatetime'] = $arr['addtime'];
        $imgs = $arr['imgs'];
        unset($arr['imgs']);
        $r = $this->add($arr);
        //发帖成功加经验
        if($r){
            if($imgs){
                //添加图片
                $imgs = explode(',', $imgs);
                $img_arr = array();
                foreach ($imgs as $k => $v) {
                    $img_arr[$k]['post_id'] = $r;
                    $img_arr[$k]['img_url'] = $v;
                }
                D('PostImg')->addPostImg($img_arr);
            }
            
            $post_exp = $GLOBALS['config_info']['POST_EXP_NUM'];
            D('UserChannelRank')->addExp($arr['user_id'], $arr['channel_id'], $post_exp);
        }
        return $r;
    }


    //wangtao 2017.9.21 帖子显示的顺序 -strat

    //获取该用户的某帖子
    public function getPostList($field =null,$where, $order=null){
        if($where){
            $where .= ' and review = 1';
        }else{
            $where = 'review = 1';
        }

        if(!$order)
        {
            $order='addtime DESC';

        }else{

            $order= $order.',addtime DESC';

        }
        return $this->field($field)->where($where)->order($order)->limit()->select();
    }

    //获取某一频道下的帖子
    public function getChannelPostList($channel_id, $order=null){

        if(!$order)
        {
            $order='is_featured DESC,addtime DESC';

        }else{
            $order= $order.',is_featured DESC,addtime DESC';

        }
        return $this->where('channel_id ='.$channel_id . ' and is_del = 0 and review = 1')->order($order)->limit()->select();
    }

    //wangtao 2017.9.21 -end


    /**
     * 帖子詳情顯示
     * @param $post_list 所有帖子的集合
     * @return mixed 返回詳情帖子的數組
     */
    public function getListData($post_list,$ques = false,$information = null){

        //wangtao 2017.9.15 -start
        $c = 0;
        $gd = '';
        $gd_1 = '';
        foreach ($information as $k => $v){
            if($information != null){

                $post_list[10 + $k]['link'] = $v['link'];
                $post_list[10 + $k]['pic'] = $v['pic'];

            }else{
                break;
            }
        }

        foreach ($post_list as $k => $v) {
//            var_dump($k,$v);
            if($ques){
                if($k == 0 && $v['is_featured'] == 1){
                    $c = 1;
                    $gd = $v;
                    $gd_1 = $post_list[0];
                    $v = $post_list[2];
                    $post_list[0] = $post_list[2];
                }else if($k == 2 && $c == 1){
                    $c = 0;
                    $v = $gd;
                    $post_list[2] = $gd_1;
                    unset($gd);
                    unset($gd_1);
                }
            }

        //wangtao 2017.9.15 -end

            $user = M('Users')->where('user_id ='.$v['user_id'])->find();
            $user_info['nickname'] = $user['nickname'];
            $user_info['headimgurl'] = $user['headimgurl'];




            $post_list[$k]['post_user'] = $user_info;
            //用户佩戴中的头衔
            $title_list = D('UserTitle')->getUserTitleList('user_id ='.$v['user_id'] .' and is_adorn = 1','adorn_time asc');
            $title_list = D('UserTitle')->getListData($title_list);
            $post_list[$k]['post_user_title'] = $title_list;
            $post_list[$k]['imgs'] = array();
            $imgs = array();

            $imgs = D('PostImg')->getPostImg($v['post_id']);

            if(count($imgs)){
                // $imgs = explode(',', $v['imgs']);
                // $post_list[$k]['imgs'] = $imgs;
                
                $post_list[$k]['img_count'] = count($imgs);
                if(count($imgs) > 6){
                    $new_imgs[0] = $imgs[0];
                    $new_imgs[1] = $imgs[1];
                    $new_imgs[2] = $imgs[2];
                    $new_imgs[3] = $imgs[3];
                    $new_imgs[4] = $imgs[4];
                    $new_imgs[5] = $imgs[5];
                    // $post_list[$k]['imgs'] = $new_imgs;
                    $imgs = $new_imgs;
                }else{
                    // $post_list[$k]['imgs'] = $imgs;
                    
                }
                foreach ($imgs as $key => $value) {
                    $imgs[$key] = array('img'=>$value, 'is_show'=>1);
                }
                $post_list[$k]['imgs'] = $imgs;
            }
            //详情和评论跳转
            $detail_url = '';
            $url_comment_list = '';
            if($v['post_type'] == self::PRAISE){ //PRAISE赞赏贴
                //后台使用
                if(!$v['is_del']){
                    $detail_url = 'post_praise_detail';
                    $url_comment_list = 'get_praise_comment_list';
                }else{
                    $detail_url = 'post_del_praise_detail';
                    $url_comment_list = 'get_del_praise_comment_list';
                }

                //赞赏价
                $price = D('PraiseHide')->getPostPraisePrice($v['post_id']);
                $post_list[$k]['praise_price'] = $price;

                //鉴定师评分
                $post_list[$k]['avg_score'] = round(D('PraiseScore')->getPostAvgScore($v['post_id']), 1);

                //帖子隐藏内容购买人数
                $hide = D('PraiseHide')->getPostHide($v['post_id']);
                $post_list[$k]['buy_num'] = D('PraiseHideBuy')->getPraiseHideBuyNum('praise_hide_id ='.$hide['praise_hide_id']);

                //如果赞赏帖主贴显示图片少于6张，则少于部分取隐藏的图片
                $total_img_num = count($post_list[$k]['imgs']);
                $hide_img_num = 6 - $total_img_num;
                $new_hide_imgs = array();
                // if($hide_img_num > 0){
                    $hide_imgs = D('PraiseHideImg')->getPraiseHideImg($hide['praise_hide_id']);
                    if(count($hide_imgs) && $hide_img_num > 0){
                        foreach ($hide_imgs as $key => $value) {
                            if($key < $hide_img_num){
                                $new_hide_imgs[] = array('img'=>$value, 'is_show'=>0);
                            }
                        }
                    }
                    
                    $post_list[$k]['img_count'] += count($hide_imgs);
                // }
                $post_list[$k]['imgs'] = array_merge($post_list[$k]['imgs'], $new_hide_imgs);
            }elseif($v['post_type'] == self::CROWDFUNDING){ // CROWDFUNDING 心愿贴
                $cf = D('Crowdfunding')->getCrowdfundingInfo('post_id ='.$v['post_id']);
                $post_list[$k]['goal_money'] = $cf['goal_money'];
                $post_list[$k]['cf_rate'] = intval($cf['now_money'] / $cf['goal_money'] * 100);
            }elseif($v['post_type'] == self::REWARD){// REWARD 悬赏贴
                $reward = D('Reward')->getRewardInfo('post_id ='.$v['post_id']);
                $post_list[$k]['reward_money'] = $reward['reward_money'];
            }elseif($v['post_type'] == self::NORMAL){
                //后台使用
                if(!$v['is_del']){
                    $detail_url = 'post_normal_detail';
                    $url_comment_list = 'get_normal_comment_list';
                }else{
                    $detail_url = 'post_del_normal_detail';
                    $url_comment_list = 'get_del_normal_comment_list';
                }
            }

            $post_list[$k]['detail_url'] = $detail_url;
            $post_list[$k]['url_comment_list'] = $url_comment_list;

            //wangtao 2017.9.15 -start
            $post_list[$k]['is_featured'] = $v['is_featured'];
            //wangtao 2017.9.15 -end

            //$post_list[$k]['addtime'] = is_today($v['addtime']) ? date('H:i', $v['addtime']) : date('Y-m-d H:i:s', $v['addtime']);
            $post_list[$k]['addtime'] = get_time($v['addtime']);

            $post_list[$k]['acp_time'] = date('Y-m-d H:i:s', $v['addtime']);
            //频道．
            $channel_obj = new ChannelModel();
            $post_list[$k]['channel_name'] = $channel_obj->getChannelField($v['channel_id'],'channel_name');

            //时间
            $post_list[$k]['year_month_day'] = date('Ymd', $v['addtime']);
            $post_list[$k]['month'] = date('m月', $v['addtime']);
            $post_list[$k]['day'] = date('d', $v['addtime']);
            $content = html_entity_decode($v['content']);
            $content = str_replace('<br>', '', $content);
            //内容截取
            $post_list[$k]['content'] = mb_substr($content, 0, 100, 'utf-8');

        }



        return $post_list;
    }

    //增加浏览量
    public function clickdotInc($post_id){
        return $this->where('post_id ='.$post_id)->setInc('clickdot');
    }

    //增加
    public function fieldInc($post_id,$field){
        return $this->where('post_id ='.$post_id)->setInc($field);
    }

    //减少
    public function fieldDec($post_id,$field){
        return $this->where('post_id ='.$post_id)->setDec($field);
    }

    //wangtao 2017.9.15 -strat
    /**
     * 获取同一频道里的精选贴数量
     * @param $pos_id
     * @return mixed
     */
    private function featuredCunte($pos_id){
        $channel_id = $this->where('post_id='.$pos_id)->select()[0]['channel_id'];
        return  $this->where('is_featured = 1 and is_del = 0 and channel_id = '.$channel_id) ->count();
    }

    /**
     * 删除精选贴
     * @param $post_id
     * @return mixed
     */
    public function delFeatured($post_id){
        return $this->where('post_id='.$post_id)->save(array('is_featured' => 0));
    }

    /**
     * 设置精选贴
     * @param $post_id
     * @return bool
     */
    public function setFeatured($post_id){
        $counts = $this->featuredCunte($post_id);
        $r = 0;
        if($counts == 0){
            $r = $this->where('post_id='.$post_id)->save(array('is_featured' => 1));
        }
        if($r){
            $post = $this->getPostInfo('post_id ='.$post_id);
            D('Message')->addMessage($post_id,4,0,$post['user_id'], '您的帖子《'.$post['title'].'》已被设置精选', '您的帖子《'.$post['title'].'》已被设置精选', '');
        }

        return $r;
    }

    //恢复帖子．
    public function recoverPost($post_id){

        $post_info = self::getPostInfo('post_id ='.$post_id);
        if($post_info['post_type'] == self::CROWDFUNDING){//心愿贴删除s
            $cf_obj = new CrowdfundingModel();
            $cf_obj->resPost($post_id);
        }

        $r = $this->where('post_id ='.$post_id)->save(array('is_del' => 0));
        if($r){
            $post = $this->getPostInfo('post_id ='.$post_id);
            D('Message')->addMessage($post_id , 4 , 0, $post['user_id'],'您的帖子《'.$post['title'].'》已被恢复', '您的帖子《'.$post['title'].'》已被恢复', '');
        }
        return $r;
    }


    /**
     * 获取当前帖子的频道分成
     * @param $post_id 帖子ID
     */
    public function getPostReatts($post_id){
        return $this->alias('p')
            ->join('tp_channel AS c ON p.channel_id = c.channel_id')
            ->field('c.channel_rates')
            ->where('p.post_id =' . $post_id)
            ->select();
    }
    //wangtao 2017.9.15 -end


    //删除帖子．
    public function delPost($post_id){
        $post_info = self::getPostInfo('post_id ='.$post_id);
        if($post_info['post_type'] == self::REWARD){ //悬赏贴删除s
            $reward_obj = new RewardModel();
            $reward_obj->delPost($post_id);
        }

        if($post_info['post_type'] == self::CROWDFUNDING){ //心愿贴删除s
            $cf_obj = new CrowdfundingModel();
            $cf_obj->delPost($post_id);
        }

        $r = $this->where('post_id ='.$post_id)->save(array('is_del' => 1, 'del_time'=>time()));
        if($r){
            $post = $this->getPostInfo('post_id ='.$post_id);
            D('Message')->addMessage($post_id, 4, 0, $post['user_id'], '您的帖子《'.$post['title'].'》已被删除', '您的帖子《'.$post['title'].'》已被删除', '');
        }
        return $r;
    }

    //判断是否点赞
    public function checkPraise($post_id){
        $user_id = intval(session('user_id'));
        $praise_num = D('Praise')->getPraiseNum('user_id ='.$user_id .' and praise_type ='.PraiseModel::POST .' and id ='.$post_id);
        $is_praise = $praise_num ? 1 : 0;
        return $is_praise;
    }

    //修改帖子内容
    public function setPost($post_id, $arr)
    {
        if (!is_numeric($post_id) || !is_array($arr)) return false;
        return $this->where('post_id = ' . $post_id)->save($arr);
    }


    //获取普通帖子详情
    public function getPostNormalInfo($post_info){


        return $post_info;

    }

    //获取赞赏帖子详情
    public function getPostPraiseInfo($post_info){

        //赞赏价
        $price = D('PraiseHide')->getPostPraisePrice($post_info['post_id']);
        $post_info['praise_price'] = $price;

        //鉴定师评分
        $post_info['avg_score'] = round(D('PraiseScore')->getPostAvgScore($post_info['post_id']), 1);

        //帖子隐藏内容购买人数
        $hide = D('PraiseHide')->getPostHide($post_info['post_id']);
        $post_info['buy_num'] = D('PraiseHideBuy')->getPraiseHideBuyNum('praise_hide_id ='.$hide['praise_hide_id']);

        //隐藏的图片
        $post_info['hide_imgs'] = D('PraiseHideImg')->getPraiseHideImgList($hide['praise_hide_id']);

        //隐藏文字
        $post_info['hide_content'] = D('PraiseHide')->getPraiseHideField('praise_hide_id ='.$hide['praise_hide_id'], 'content');

        $post_info['praise_hide_id'] = $hide['praise_hide_id'];

        return $post_info;

    }

    //获取悬赏帖子详情
    public function getPostRewardInfo($post_info){
        $reward_obj = new RewardModel();
        $reward_info = $reward_obj->getRewardInfo('post_id ='.$post_info['post_id']);
        //时间
        $reward_info['acp_time'] = date('Y-m-d H:i:s', $reward_info['addtime']);
        $reward_info['acp_end_time'] = date('Y-m-d H:i:s', $reward_info['end_time']);
        $post_info['reward_info'] = $reward_info;
        //悬赏状态
        $state='';
        if ($reward_info['status'] == RewardModel::REWARDING) {
            $state = '悬赏中';
        }elseif ($reward_info['status'] == RewardModel::ADOPTED){
            $state = '已采纳';
        }elseif ($reward_info['status'] == RewardModel::NOT_ADOPTED){
            $state = '未采纳';
        }elseif ($reward_info['status'] == RewardModel::REFUNDING){
            $state = '退款中';
        }elseif ($reward_info['status'] == RewardModel::REFUNDED){
            $state = '已退款';
        }
        $post_info['state'] = $state;

        //邀请的用户
        $user_obj = new UserModel();
        $post_info['invite_name'] = $user_obj->getUserFields('nickname','user_id in ('.$reward_info['invite_users'].')');

        //被采纳的用户
        $post_info['adopted_name'] = $user_obj->getUserField('nickname','user_id  = '.$reward_info['adopted_user']);

        //被采纳的答案
        $reward_answer_obj = new RewardAnswerModel();
        $adopted_answer = $reward_answer_obj->getRewardAnswerInfo('reward_id ='.$reward_info['reward_id']);
        $adopted_answer['adopted_time'] = date('Y-m-d H:i:s', $adopted_answer['addtime']);
        $post_info['adopted_answer'] = $adopted_answer;
        //被采纳的答案图片
        $answer_img_obj = new RewardAnswerImgModel();
        $post_info['answer_img_list'] =$answer_img_obj->getRewardAnswerImgList('reward_answer_id ='.$adopted_answer['reward_answer_id']);

        return $post_info;

    }

    //获取心愿帖子详情
    public function getPostCrowdFundingInfo($post_info){
        //心愿信息
        $cf_obj = new CrowdfundingModel();
        $cf_info = $cf_obj->getCrowdfundingInfo('post_id ='.$post_info['post_id']);
        //时间
        $cf_info['acp_time'] = date('Y-m-d H:i:s', $cf_info['addtime']);
        $cf_info['acp_pass_time'] = date('Y-m-d H:i:s', strtotime($cf_info['pass_time']));
        $cf_info['acp_end_time'] = date('Y-m-d H:i:s', strtotime($cf_info['end_time']));

        $post_info['cf_info'] = $cf_info;
        //心愿状态
        $state='';
        if ($cf_info['status'] == CrowdfundingModel::REVIEW) {
            $state = '待审核';
        }elseif ($cf_info['status'] == CrowdfundingModel::PASSED){
            $state = '进行中';
        }elseif ($cf_info['status'] == CrowdfundingModel::SUCCESS){
            $state = '成功';
        }elseif ($cf_info['status'] == CrowdfundingModel::FAILURE){
            $state = '失败';
        }
        $post_info['state'] = $state;

        //楼主回帖信息
        $cf_reply_obj = new CfReplyModel();
        $reply_info = $cf_reply_obj ->getCfReplyInfo('post_id ='.$post_info['post_id']);
        $reply_info['reply_time'] = date('Y-m-d H:i:s', $cf_info['addtime']);
        $post_info['reply_info'] = $reply_info;
        $post_info['reply_img_list'] =  D('CfReplyImg')->getCfReplyImgList($reply_info['cf_reply_id']);

        return $post_info;

    }

    public function getTitleById($post_id){
        return $this->where('post_id ='.$post_id)->getField('title');
    }


}
